package com.zhj.psi.web.controller;

import com.zhj.psi.core.config.PageRange;
import com.zhj.psi.core.mvc.AjaxResult;
import com.zhj.psi.core.mvc.JsonArg;
import com.zhj.psi.core.tools.PageHelper;
import com.zhj.psi.web.dto.SecurityUser;
import com.zhj.psi.web.entity.User;
import com.zhj.psi.web.repository.UserDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * Created by zhuhuijun on 2017/8/31 15:10
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserDao userDao;

    @RequestMapping("/findUserInfo")
    @PreAuthorize("")
    public AjaxResult findUserInfo() {
        SecurityUser userDetails = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        logger.info("Test:===={}", userDetails.getUsername());
        return new AjaxResult().with(userDetails);
    }

    @PreAuthorize("")
    @RequestMapping("/list")
    public AjaxResult list(@JsonArg("user") User user, @JsonArg("pageRange") PageRange pageRange) {
        return new AjaxResult().with(userDao.findAll(PageHelper.buildPageRequest(pageRange)));
    }

    @PreAuthorize("")
    @RequestMapping("/add")
    public AjaxResult add(@JsonArg("user") User user) {
        userDao.save(user);
        return new AjaxResult();
    }

    @PreAuthorize("")
    @RequestMapping("/find")
    public AjaxResult find(@JsonArg("id") long id) {
        return new AjaxResult().with(userDao.findOne(id));
    }

    @PreAuthorize("")
    @RequestMapping("/delete")
    public AjaxResult delete(@JsonArg("id") long id) {
        userDao.delete(id);
        return new AjaxResult();
    }


}
